package com.designpattern.singleton;

/**
 * @Classname SingletonThreadTest
 * @Description 单例模式多线程验证，验证饿汉模式线程安全、懒汉模式线程不安全
 * @Date 2019/5/11 23:20
 * @Created by xiangty
 */
public class SingletonThreadTest implements Runnable{

    public static void main(String[] args) throws Exception {
        SingletonThreadTest singletonThreadTest = new SingletonThreadTest();
        Thread thread1 = new Thread(singletonThreadTest);
        Thread thread2 = new Thread(singletonThreadTest);
        Thread thread3 = new Thread(singletonThreadTest);
        Thread thread4 = new Thread(singletonThreadTest);
        Thread thread5 = new Thread(singletonThreadTest);
        Thread thread6 = new Thread(singletonThreadTest);
        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
        thread5.start();
        thread6.start();

        thread1.join();
        thread2.join();
        thread3.join();
        thread4.join();
        thread5.join();
        thread6.join();
    }

    /**
     * 验证饿汉模式
     */
    public static void method1(){
        Singleton1 singleton1 = Singleton1.getInstance();
        Singleton1 singleton2 = Singleton1.getInstance();

        if(singleton1 == singleton2){
            println(Thread.currentThread().getName()+"饿汉模式:singleton1和singleton2是同一个实例");
        } else {
            println(Thread.currentThread().getName()+"饿汉模式:singleton1和singleton2不是同一个实例");
        }
    }

    /**
     * 验证懒汉模式
     */
    public static void method2(){
        Singleton2 singleton1 = Singleton2.getInstance();
        Singleton2 singleton2 = Singleton2.getInstance();

        if(singleton1 == singleton2){
            println(Thread.currentThread().getName()+"懒汉模式:singleton1和singleton2是同一个实例");
        } else {
            println(Thread.currentThread().getName()+"懒汉模式:singleton1和singleton2不是同一个实例");
        }
    }

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            method2();
        }
    }

    /**
     * 输出信息
     */
    private static void println(Object obj){
        System.out.println(obj);
    }

}
